import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { i18n } from "../i18n";

export const useAppStore = defineStore("app", () => {
  // 状态
  const theme = ref<"light" | "dark">(
    (localStorage.getItem("theme") as "light" | "dark") || "light",
  );
  const locale = ref<"zh-CN" | "en-US">(
    (localStorage.getItem("locale") as "zh-CN" | "en-US") || "zh-CN",
  );
  const loading = ref(false);
  const sidebarCollapsed = ref(false);

  // 添加loading状态保护
  let loadingTimer: ReturnType<typeof setTimeout> | null = null;

  // 计算属性
  const isDark = computed(() => theme.value === "dark");
  const isZhCN = computed(() => locale.value === "zh-CN");

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    theme.value = theme.value === "light" ? "dark" : "light";
    localStorage.setItem("theme", theme.value);

    // 更新HTML根元素的data-theme属性
    document.documentElement.setAttribute("data-theme", theme.value);
  };

  /**
   * 设置主题
   */
  const setTheme = (newTheme: "light" | "dark") => {
    theme.value = newTheme;
    localStorage.setItem("theme", newTheme);
    document.documentElement.setAttribute("data-theme", newTheme);
  };

  /**
   * 切换语言
   */
  const toggleLocale = () => {
    locale.value = locale.value === "zh-CN" ? "en-US" : "zh-CN";
    localStorage.setItem("locale", locale.value);

    // 更新i18n语言
    i18n.global.locale.value = locale.value;
  };

  /**
   * 设置语言
   */
  const setLocale = (newLocale: "zh-CN" | "en-US") => {
    locale.value = newLocale;
    localStorage.setItem("locale", newLocale);

    // 更新i18n语言
    i18n.global.locale.value = newLocale;
  };

  /**
   * 设置加载状态
   */
  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading;

    // 如果设置为加载中，添加5秒后自动重置的保护
    if (isLoading) {
      if (loadingTimer) {
        clearTimeout(loadingTimer);
      }
      loadingTimer = setTimeout(() => {
        console.warn("Loading状态超时，自动重置");
        loading.value = false;
        loadingTimer = null;
      }, 5000);
    } else {
      // 如果设置为非加载状态，清除定时器
      if (loadingTimer) {
        clearTimeout(loadingTimer);
        loadingTimer = null;
      }
    }
  };

  /**
   * 切换侧边栏折叠状态
   */
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value;
    localStorage.setItem("sidebarCollapsed", String(sidebarCollapsed.value));
  };

  /**
   * 初始化应用设置
   */
  const initApp = () => {
    // 初始化主题
    document.documentElement.setAttribute("data-theme", theme.value);

    // 初始化侧边栏状态
    const savedSidebarState = localStorage.getItem("sidebarCollapsed");
    if (savedSidebarState) {
      sidebarCollapsed.value = savedSidebarState === "true";
    }

    // 初始化语言
    i18n.global.locale.value = locale.value;
  };

  /**
   * 显示全局加载
   */
  const showLoading = () => {
    setLoading(true);
  };

  /**
   * 隐藏全局加载
   */
  const hideLoading = () => {
    setLoading(false);
  };

  /**
   * 异步操作包装器，自动处理加载状态
   */
  const withLoading = async <T>(
    asyncFn: () => Promise<T>,
    showGlobalLoading = true,
  ): Promise<T> => {
    try {
      if (showGlobalLoading) {
        showLoading();
      }
      return await asyncFn();
    } finally {
      if (showGlobalLoading) {
        hideLoading();
      }
    }
  };

  return {
    // 状态
    theme,
    locale,
    loading,
    sidebarCollapsed,

    // 计算属性
    isDark,
    isZhCN,

    // 方法
    toggleTheme,
    setTheme,
    toggleLocale,
    setLocale,
    setLoading,
    toggleSidebar,
    initApp,
    showLoading,
    hideLoading,
    withLoading,
  };
});
